package com.example.geoaimavlink_android.activity.fragment

import android.graphics.Point
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.example.geoaimavlink_android.R
import com.geoai.mavlink.geoainet.base.mavlinkcore.engine.GEOAIError
import com.geoai.mavlink.geoainet.base.mavlinkcore.interfaces.CompletionCallback.ICompletionCallbackWith
import kotlinx.android.synthetic.main.frag_rally.btn_add_target
import kotlinx.android.synthetic.main.frag_rally.btn_delete_index
import kotlinx.android.synthetic.main.frag_rally.btn_gohome_index
import kotlinx.android.synthetic.main.frag_rally.btn_refresh_rally
import kotlinx.android.synthetic.main.frag_rally.edt_add_target_x
import kotlinx.android.synthetic.main.frag_rally.edt_add_target_y
import kotlinx.android.synthetic.main.frag_rally.edt_gohome_index
import kotlinx.android.synthetic.main.frag_rally.edt_remove_index
import kotlinx.android.synthetic.main.frag_rally.ll_rally_list
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class RallyFragment: BaseFragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return View.inflate(context, R.layout.frag_rally, null)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        initSDK()
    }

    private fun initSDK() {
        msdkInfoVm.msdkInfo.observe(viewLifecycleOwner) {
            if (it.isAircraftConnected) {
                getProduct()?.flyControllerManager?.setFlyControllerStateListener {

                }
            }
        }
    }

    override fun onDestroyView() {
        msdkInfoVm.msdkInfo.removeObservers(viewLifecycleOwner)
        getProduct()?.flyControllerManager?.setFlyControllerStateListener(null)
        super.onDestroyView()
    }

    private fun initView() {
        btn_gohome_index.setOnClickListener {
            if (edt_gohome_index.text.isEmpty()) return@setOnClickListener
            getProduct()?.flyControllerManager?.startAircraftReturnAssignRally(edt_gohome_index.text.toString().toInt()) {
                showToast(it?.description?:"success")
            }
        }
        btn_delete_index.setOnClickListener {
            if (edt_remove_index.text.isEmpty()) return@setOnClickListener
            val index = edt_remove_index.text.toString().toInt()
            val listSender = mutableListOf<Point>()
            for (i in 0..ll_rally_list.childCount) {
                if (i == index) continue
                val tv = ll_rally_list.getChildAt(i)
                if (tv is TextView) {
                    val location = tv.text.toString()
                    location.split("-").let {
                        val x = it[0].toInt()
                        val y = it[1].toInt()
                        listSender.add(Point(x, y))
                    }
                }
            }
            //设置备降坐标
            getProduct()?.flyControllerManager?.setAlternateLandingPoints(listSender.toTypedArray()) {
                showToast(it?.description?:"success")
                GlobalScope.launch {
                    delay(1000)
                    mainHandler.post { btn_refresh_rally.performClick() }
                }
            }
        }
        btn_add_target.setOnClickListener {
            if (edt_add_target_x.text.isEmpty()) return@setOnClickListener
            if (edt_add_target_y.text.isEmpty()) return@setOnClickListener
            //获取当前的所有点
            val listSender = mutableListOf<Point>()
            for (i in 0..ll_rally_list.childCount) {
                val tv = ll_rally_list.getChildAt(i)
                if (tv is TextView) {
                    val location = tv.text.toString()
                    location.split("-").let {
                        val x = it[0].toInt()
                        val y = it[1].toInt()
                        listSender.add(Point(x, y))
                    }
                }
            }
            //添加文本点
            listSender.add(Point(
                (edt_add_target_x.text.toString().toDouble() * 10000000).toInt(),
                (edt_add_target_y.text.toString().toDouble() * 10000000).toInt()))
            //设置备降坐标
            getProduct()?.flyControllerManager?.setAlternateLandingPoints(listSender.toTypedArray()) {
                showToast(it?.description?:"success")
            }
        }
        btn_refresh_rally.setOnClickListener {
            ll_rally_list.removeAllViews()
            getProduct()?.flyControllerManager?.getAlternateLandingPoints(object : ICompletionCallbackWith<Array<Point>> {
                override fun onFailure(geoaiError: GEOAIError?) {
                    showToast(geoaiError?.description?:"error.")
                }

                override fun onResult(points: Array<Point>?) {
                    showToast("success: ${points?.size?:0}")
                    points?.let {points ->
                        points.forEach {
                            val tv = TextView(context)
                            tv.text = "${it.x}-${it.y}"
                            ll_rally_list.addView(tv)
                        }
                    }
                }
            })
        }
    }
}